package cn.xkai.exercise.b;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @description: 钥匙和房间
 * 自己的思路：把进过房间的钥匙都放到队列中，依此通过已找到的钥匙进入房间，然后把钥匙继续放到队列中...判断访问次数是否等于房间数
 * 借鉴的思路：dfs深度优先解法，直接判断当前房间未访问并访问次数加1，最后判断访问次数是否等于房间数
 * 心得：bfs-队列的入队出队操作耗费时间、dfs-递归时耗费内存栈
 * @author: kaixiang
 * @date: 2022/7/23
 **/
public class Solution88 {
    private int visitCounter = 0;
    private boolean[] visited;

    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        visited = new boolean[rooms.size()];
        bfs(rooms);
        dfs(rooms, 0);
        return visitCounter == visited.length;
    }

    private void bfs(List<List<Integer>> rooms) {
        visited[0] = true;
        visitCounter = 1;
        Queue<Integer> queue = new LinkedList<>(rooms.get(0));
        while (!queue.isEmpty()) {
            int room = queue.poll();
            if (visited[room]) {
                continue;
            }
            for (int key : rooms.get(room)) {
                if (!visited[key]) {
                    queue.add(key);
                }
            }
            visited[room] = true;
            visitCounter++;
        }
    }

    private void dfs(List<List<Integer>> rooms, int index) {
        visited[index] = true;
        visitCounter++;
        for (int i : rooms.get(index)) {
            if (!visited[i]) {
                dfs(rooms, i);
            }
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> rooms = new ArrayList<>();
        List<Integer> room1 = new ArrayList<>();
        room1.add(1);
        room1.add(1);
        List<Integer> room2 = new ArrayList<>();
        room2.add(2);
        room2.add(2);
        room2.add(2);
        List<Integer> room3 = new ArrayList<>();
        room3.add(3);
        List<Integer> room4 = new ArrayList<>();
        room4.add(0);
        rooms.add(room1);
        rooms.add(room2);
        rooms.add(room3);
        rooms.add(room4);
        Solution88 solution88 = new Solution88();
        System.out.println(solution88.canVisitAllRooms(rooms));
    }
}
